import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import enUS from 'antd/lib/locale/en_US';
import { I18nProvider, useI18n } from './contexts/I18nContext';
import { checkAuth } from './services/api';
import Login from './components/Login';
import DeviceList from './components/DeviceList';
import DeviceDetail from './components/DeviceDetail';
import 'antd/dist/antd.css';

const AppContent = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const { language } = useI18n();

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token && checkAuth()) {
      setIsAuthenticated(true);
    }
    setLoading(false);
  }, []);

  const handleLoginSuccess = () => {
    setIsAuthenticated(true);
  };

  const handleLogout = () => {
    setIsAuthenticated(false);
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <ConfigProvider locale={language === 'zh' ? zhCN : enUS}>
      <Router>
        <Routes>
          <Route 
            path="/login" 
            element={
              isAuthenticated ? 
              <Navigate to="/devices" replace /> : 
              <Login onLoginSuccess={handleLoginSuccess} />
            } 
          />
          <Route 
            path="/devices" 
            element={
              isAuthenticated ? 
              <DeviceList onLogout={handleLogout} /> : 
              <Navigate to="/login" replace />
            } 
          />
          <Route 
            path="/device/:deviceId" 
            element={
              isAuthenticated ? 
              <DeviceDetail onLogout={handleLogout} /> : 
              <Navigate to="/login" replace />
            } 
          />
          <Route 
            path="/" 
            element={<Navigate to={isAuthenticated ? "/devices" : "/login"} replace />} 
          />
        </Routes>
      </Router>
    </ConfigProvider>
  );
};

const App = () => {
  return (
    <I18nProvider>
      <AppContent />
    </I18nProvider>
  );
};

export default App; 